package org.aeon.colorfulplanebattle.view.logic;

import org.aeon.colorfulplanebattle.constant.GameStateE;
import org.aeon.colorfulplanebattle.flying.entity.Bullet;
import org.aeon.colorfulplanebattle.flying.entity.CollisionPairs;
import org.aeon.colorfulplanebattle.flying.entity.Plane;
import org.aeon.colorfulplanebattle.flying.entity.Ship;
import org.aeon.colorfulplanebattle.view.GameState;
import org.aeon.colorfulplanebattle.view.components.PopUp;
import org.aeon.colorfulplanebattle.view.panel.SettlementPage;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Deque;
import java.util.List;
import java.util.TimerTask;

/**
 * @author: MissingAeon
 * @date: 2024/1/9 12:37
 * @description:
 */
public class FlyDrawTask extends TimerTask {
    private final JComponent component;                     // 绘画组件
    private final GameState gameState;                      // 游戏状态类
    private final List<Ship> ships;                         // 敌方飞机
    private final List<Bullet> bullets;                     // 所有子弹
    private final Deque<CollisionPairs> hit;                // 所有命中
    private final Plane myPlane;                            // 玩家飞机


    public FlyDrawTask(GameState gameState, Plane myPlane, List<Ship> ships, List<Bullet> bullets, Deque<CollisionPairs> hit) {
        // this.setName("飞行管理线程");
        this.myPlane = myPlane;
        this.gameState = gameState;
        this.component = this.gameState.get("Battlefield");
        this.ships = ships;
        this.bullets = bullets;
        this.hit = hit;
    }

    public void drawAll(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        // 抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 创建带缓冲区图像
        BufferedImage bi = new BufferedImage(component.getHeight(), component.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        // 可以理解为获取临时画布
        Graphics tmp_g = bi.getGraphics();
        // 背景覆盖
        tmp_g.setColor(new Color(210, 253, 245));
        tmp_g.fillRect(0, 0, component.getHeight(), component.getHeight());
        // 绘制己方飞机
        myPlane.draw(tmp_g);
        // 绘制敌方方飞机
        ships.forEach(ship -> ship.draw(tmp_g));
        // 绘制子弹
        bullets.forEach(bullet -> bullet.draw(tmp_g));
        // 绘制命中
        hit.forEach(collisionPairs -> collisionPairs.draw(tmp_g));
        // 组件绘制
        g2d.drawImage(bi, 0, 0, null);
        g2d.dispose();
    }

    /**
     * 这里完成刷新工作
     */
    @Override
    public void run() {
        while (true) {
            component.repaint();
            if (myPlane.isDestroy()) {
                break;
            }
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        TaskManage.finish();
    }

    @Override
    public boolean cancel() {
        // 结算
        return super.cancel();
    }
}


